package menu

import (
	"context"
	"go-zero-project/services/user/rpc/internal/mapper"
	"go-zero-project/services/user/rpc/internal/mapper/bo"
	"go-zero-project/services/user/rpc/internal/svc"
	"go-zero-project/services/user/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type MenuPageListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewMenuPageListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MenuPageListLogic {
	return &MenuPageListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *MenuPageListLogic) MenuPageList(in *pb.MenuPageListReq) (*pb.MenuPageListResp, error) {
	// 1.1 count
	menuBO := bo.SysMenuBO{ParentId: 0, NoParentId: false, UrlLike: in.Url,
		PermsLike: in.Perms, Type: int(in.MenuType)}
	menuMapper := mapper.NewMenuMapper()
	selectCount, err := menuMapper.SelectCount(l.svcCtx.DBEngin, menuBO)
	if err != nil {
		return nil, err
	}
	resp := new(pb.MenuPageListResp)
	resp.TotalPage = int32(selectCount)
	resp.CurrentPage = in.PageNum
	// 1.2 if no exist return
	if selectCount <= 0 {
		return resp, err
	}
	// 1.3 query List
	// 设置分页信息
	pageNum := in.PageNum
	pageSize := in.PageSize
	startPageIndex := 0
	if pageNum > 1 {
		startPageIndex = int((pageNum - 1) * pageSize)
	}
	menuBO.StartIndex = startPageIndex
	menuBO.PageSize = int(pageSize)
	menuRootArr, err := menuMapper.SelectList(l.svcCtx.DBEngin, menuBO)
	if err != nil {
		logx.Errorf("mapper.NewMenuPageListLogic().QueryListParentId failed:%s", err.Error())
		return nil, err
	}
	// 2.return obj ...
	var navArr []*pb.MenuInfoResp
	for _, v := range menuRootArr {
		navArr = append(navArr, &pb.MenuInfoResp{
			MenuId:   v.MenuId,
			ParentId: v.ParentId.Int64,
			Name:     v.Name,
			Url:      v.Url,
			Perms:    v.Perms,
			MenuType: int32(v.Type.Int16),
			Icon:     v.Icon,
			OrderNum: v.OrderNum.Int32,
		})
	}
	resp.Data = navArr
	return resp, nil
}
